package com.csun.dsms.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.csun.dsms.comment.core.utils.wrapper.WrapMapper;
import com.csun.dsms.comment.core.utils.wrapper.Wrapper;
import com.csun.dsms.mapper.IhgGovernmentServiceMapper;
import com.csun.dsms.mapper.IhgSocialServiceMapper;
import com.csun.dsms.mapper.IhgUserMapper;
import com.csun.dsms.model.huang.*;
import com.csun.dsms.service.IhgDataProcessService;
import com.csun.dsms.utils.pt.HuangGangUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.NumberFormat;
import java.util.*;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.stream.Collectors;

@Slf4j
@Service
public class IhgDataProcessServiceImpl implements IhgDataProcessService {

    @Resource
    private IhgUserMapper ihgUserMapper;
    @Resource
    private IhgGovernmentServiceMapper ihgGovernmentServiceMapper;
    @Resource
    private IhgSocialServiceMapper ihgSocialServiceMapper;

    private static final List<String> DEPARTMENT_NAME = CollectionUtil.newArrayList(
            "市文旅局", "市人社局", "市供应链公司", "市商务局", "市农业农村局", "市教育局", "市司法局",
            "市住房公积金中心", "市住房和城市更新局", "市生态环境局", "市委组织部（市政数局）", "市总工会",
            "市医疗保障局", "市地方金融工作局", "市卫健委", "市人大", "市社会工作部", "市民政局"
    );

    @Override
    public IhgUser loginCheck(String iHgToken) {
        String aesRes = HuangGangUtil.login(iHgToken);
        JSONObject aesJsonBean = JSONObject.parseObject(aesRes);
        if (aesJsonBean != null && aesJsonBean.getString("userId") != null) {
            String mobilePhone = aesJsonBean.getString("mobilePhone");
            IhgUser ihgUser = ihgUserMapper.selectIhgUserByPhone(mobilePhone);
            return ihgUser;
        }
        return null;
    }

    @Override
    public IhgUser loginByPhone(String phone) {
        IhgUser ihgUser = ihgUserMapper.selectIhgUserByPhone(phone);
        return ihgUser;
    }

    @Override
    public Wrapper queryGovernmentData(PageParameter<IhgGovernmentServiceBean> ihgGovernmentServiceBeanPage) {
        try {
            int pageNum = ihgGovernmentServiceBeanPage.getPageNum();
            int pageSize = ihgGovernmentServiceBeanPage.getPageSize();
            IhgGovernmentServiceBean data = ihgGovernmentServiceBeanPage.getData();
            PageInfo<IhgGovernmentServiceBean> ihgGovernmentServiceBeanPageInfo = PageHelper.startPage(pageNum, pageSize).doSelectPageInfo(() -> ihgGovernmentServiceMapper.queryListWithPage(data));
            List<IhgGovernmentServiceBean> list = ihgGovernmentServiceBeanPageInfo.getList();
            return WrapMapper.wrap(Wrapper.SUCCESS_CODE, Wrapper.SUCCESS_MESSAGE, list);
        } catch (Exception e) {
            log.error("查询政府服务数据报错", e);
            return WrapMapper.wrap(Wrapper.ERROR_CODE, e.getMessage());
        }
    }

    @Override
    public PageInfo queryGovernmentPage(IHgQueryDto iHgQueryDto) {
        PageHelper.startPage(iHgQueryDto.getPageNum(),iHgQueryDto.getPageSize());
        List<IhgGovernmentServiceBean> list = ihgGovernmentServiceMapper.selectByPage(iHgQueryDto);
//         list = distinctByGovernmentProjectName(list);
        return new PageInfo(list);
    }

    @Override
    public PageInfo querySocialPage(IHgQueryDto iHgQueryDto) {
        PageHelper.startPage(iHgQueryDto.getPageNum(),iHgQueryDto.getPageSize());
        List<IhgSocialServiceBean> list = ihgSocialServiceMapper.selectByPage(iHgQueryDto);
//         list = distinctBySocialProjectName(list);
        return new PageInfo(list);
    }

    @Override
    public Wrapper addGovernmentData(IhgGovernmentServiceBean ihgGovernmentServiceBean) {
        try {
            ihgGovernmentServiceMapper.addData(ihgGovernmentServiceBean);
            return WrapMapper.wrap(Wrapper.SUCCESS_CODE, Wrapper.SUCCESS_MESSAGE);
        } catch (Exception e) {
            log.error("新增政府服务数据报错", e);
            return WrapMapper.wrap(Wrapper.ERROR_CODE, e.getMessage());
        }
    }

    @Override
    public Wrapper updateGovernmentData(IhgGovernmentServiceBean ihgGovernmentServiceBean) {
        try {
            Long id = ihgGovernmentServiceBean.getId();
            if (id == null) {
                return WrapMapper.wrap(Wrapper.ERROR_CODE, "id禁止为空！");
            }
            ihgGovernmentServiceMapper.updateData(ihgGovernmentServiceBean);
            return WrapMapper.wrap(Wrapper.SUCCESS_CODE, Wrapper.SUCCESS_MESSAGE);
        } catch (Exception e) {
            log.error("修改政府服务数据报错", e);
            return WrapMapper.wrap(Wrapper.ERROR_CODE, e.getMessage());
        }
    }

    @Override
    public Wrapper deleteGovernmentData(IhgGovernmentServiceBean ihgGovernmentServiceBean) {
        try {
            Long id = ihgGovernmentServiceBean.getId();
            if (id == null) {
                return WrapMapper.wrap(Wrapper.ERROR_CODE, "id禁止为空！");
            }
            ihgGovernmentServiceMapper.deleteData(ihgGovernmentServiceBean);
            return WrapMapper.wrap(Wrapper.SUCCESS_CODE, Wrapper.SUCCESS_MESSAGE);
        } catch (Exception e) {
            log.error("删除政府服务数据报错", e);
            return WrapMapper.wrap(Wrapper.ERROR_CODE, e.getMessage());
        }
    }

    @Override
    public Wrapper querySocialData(PageParameter<IhgSocialServiceBean> ihgSocialServiceBeanPage) {
        try {
            int pageNum = ihgSocialServiceBeanPage.getPageNum();
            int pageSize = ihgSocialServiceBeanPage.getPageSize();
            IhgSocialServiceBean data = ihgSocialServiceBeanPage.getData();
            PageInfo<IhgSocialServiceBean> ihgSocialServiceBeanPageInfo = PageHelper.startPage(pageNum, pageSize).doSelectPageInfo(() -> ihgSocialServiceMapper.queryListWithPage(data));
            List<IhgSocialServiceBean> list = ihgSocialServiceBeanPageInfo.getList();
            return WrapMapper.wrap(Wrapper.SUCCESS_CODE, Wrapper.SUCCESS_MESSAGE, list);
        } catch (Exception e) {
            log.error("查询社会服务数据报错", e);
            return WrapMapper.wrap(Wrapper.ERROR_CODE, e.getMessage());
        }
    }

    @Override
    public Wrapper addSocialData(IhgSocialServiceBean ihgSocialServiceBean) {
        try {
            ihgSocialServiceMapper.addData(ihgSocialServiceBean);
            return WrapMapper.wrap(Wrapper.SUCCESS_CODE, Wrapper.SUCCESS_MESSAGE);
        } catch (Exception e) {
            log.error("新增社会服务数据报错", e);
            return WrapMapper.wrap(Wrapper.ERROR_CODE, e.getMessage());
        }
    }

    @Override
    public Wrapper updateSocialData(IhgSocialServiceBean ihgSocialServiceBean) {
        try {
            Long id = ihgSocialServiceBean.getId();
            if (id == null) {
                return WrapMapper.wrap(Wrapper.ERROR_CODE, "id禁止为空！");
            }
            ihgSocialServiceMapper.updateData(ihgSocialServiceBean);
            return WrapMapper.wrap(Wrapper.SUCCESS_CODE, Wrapper.SUCCESS_MESSAGE);
        } catch (Exception e) {
            log.error("修改社会服务数据报错", e);
            return WrapMapper.wrap(Wrapper.ERROR_CODE, e.getMessage());
        }
    }

    @Override
    public Wrapper deleteSocialData(IhgSocialServiceBean ihgSocialServiceBean) {
        try {
            Long id = ihgSocialServiceBean.getId();
            if (id == null) {
                return WrapMapper.wrap(Wrapper.ERROR_CODE, "id禁止为空！");
            }
            ihgSocialServiceMapper.deleteData(ihgSocialServiceBean);
            return WrapMapper.wrap(Wrapper.SUCCESS_CODE, Wrapper.SUCCESS_MESSAGE);
        } catch (Exception e) {
            log.error("删除社会服务数据报错", e);
            return WrapMapper.wrap(Wrapper.ERROR_CODE, e.getMessage());
        }
    }

    @Override
    public Wrapper queryStatistical(JSONObject reqJson) {
        NumberFormat nt = NumberFormat.getPercentInstance();
        nt.setMinimumFractionDigits(5);
        try {
            List<String> areaNames = CollectionUtil.newArrayList();
            List<JSONObject> resJsonList = CollectionUtil.newArrayList();
            Boolean isGrowth = reqJson.getBoolean("isGrowth");
            Date startTime = reqJson.getDate("startTime");
            Date endTime = reqJson.getDate("endTime");
            if (isGrowth == null) {
                return WrapMapper.wrap(Wrapper.ERROR_CODE, "是否增长不能为空！");
            }
            if (isGrowth) {
                if (startTime == null || endTime == null) {
                    return WrapMapper.wrap(Wrapper.ERROR_CODE, "起始时间和结束时间为空！");
                }
                List<IhgGovernmentServiceBean> ihgGovernmentServiceBeans = ihgGovernmentServiceMapper.queryDateByTime(reqJson);
                List<IhgSocialServiceBean> ihgSocialServiceBeans = ihgSocialServiceMapper.queryDateByTime(reqJson);
                List<IhgGovernmentServiceBean> ihgGovernmentServiceBeansNew = distinctByGovernmentProjectName(ihgGovernmentServiceBeans);
                List<IhgSocialServiceBean> ihgSocialServiceBeansNew = distinctBySocialProjectName(ihgSocialServiceBeans);
                List<IhgGovernmentServiceBean> ihgGovernmentServiceBeansOld = distinctByGovernmentProjectNameOld(ihgGovernmentServiceBeans);
                List<IhgSocialServiceBean> ihgSocialServiceBeansOld = distinctBySocialProjectNameOld(ihgSocialServiceBeans);
                List<String> areaGovernmentNames = ihgGovernmentServiceBeans.stream().map(IhgGovernmentServiceBean::getAreaName).collect(Collectors.toList());
                List<String> areaSocialNames = ihgSocialServiceBeans.stream().map(IhgSocialServiceBean::getAreaName).collect(Collectors.toList());
                areaNames.addAll(areaGovernmentNames);
                areaNames.addAll(areaSocialNames);
                areaNames = areaNames.stream().distinct().collect(Collectors.toList());
                for (String areaName : areaNames) {
                    JSONObject resStatisticalJson = new JSONObject();
                    List<IhgGovernmentServiceBean> ihgGovernmentServiceNewByAres = ihgGovernmentServiceBeansNew.stream().filter(IhgGovernmentServiceBean -> areaName.equals(IhgGovernmentServiceBean.getAreaName())).collect(Collectors.toList());
                    List<IhgGovernmentServiceBean> ihgGovernmentServiceOldByAres = ihgGovernmentServiceBeansOld.stream().filter(IhgGovernmentServiceBean -> areaName.equals(IhgGovernmentServiceBean.getAreaName())).collect(Collectors.toList());
                    List<IhgSocialServiceBean> ihgSocialServiceNewByAres = ihgSocialServiceBeansNew.stream().filter(IhgSocialServiceBean -> areaName.equals(IhgSocialServiceBean.getAreaName())).collect(Collectors.toList());
                    List<IhgSocialServiceBean> ihgSocialServiceOldByAres = ihgSocialServiceBeansOld.stream().filter(IhgSocialServiceBean -> areaName.equals(IhgSocialServiceBean.getAreaName())).collect(Collectors.toList());
                    int governmentAllOrderCountSum = ihgGovernmentServiceNewByAres.stream()
                            .map(IhgGovernmentServiceBean::getAllOrderCount)
                            .filter(Objects::nonNull)
                            .mapToInt(Integer::intValue)
                            .sum()
                            -
                            ihgGovernmentServiceOldByAres.stream()
                                    .map(IhgGovernmentServiceBean::getAllOrderCount)
                                    .filter(Objects::nonNull)
                                    .mapToInt(Integer::intValue)
                                    .sum();
                    int governmentIhgOrderCountSum = ihgGovernmentServiceNewByAres.stream()
                            .map(IhgGovernmentServiceBean::getIhgOrderCount)
                            .filter(Objects::nonNull)
                            .mapToInt(Integer::intValue)
                            .sum()
                            -
                            ihgGovernmentServiceOldByAres.stream()
                                    .map(IhgGovernmentServiceBean::getIhgOrderCount)
                                    .filter(Objects::nonNull)
                                    .mapToInt(Integer::intValue)
                                    .sum();
                    int socialOrderCountSum = ihgSocialServiceNewByAres.stream()
                            .map(IhgSocialServiceBean::getOrderCount)
                            .filter(Objects::nonNull)
                            .mapToInt(Integer::intValue)
                            .sum()
                            -
                            ihgSocialServiceOldByAres.stream()
                                    .map(IhgSocialServiceBean::getOrderCount)
                                    .filter(Objects::nonNull)
                                    .mapToInt(Integer::intValue)
                                    .sum();
                    int socialEnterMarketCountSum = ihgSocialServiceNewByAres.stream()
                            .map(IhgSocialServiceBean::getEnterMarketCount)
                            .filter(Objects::nonNull)
                            .mapToInt(Integer::intValue)
                            .sum()
                            -
                            ihgSocialServiceOldByAres.stream()
                                    .map(IhgSocialServiceBean::getEnterMarketCount)
                                    .filter(Objects::nonNull)
                                    .mapToInt(Integer::intValue)
                                    .sum();
                    int socialOnlineServiceCountSum = ihgSocialServiceNewByAres.stream()
                            .map(IhgSocialServiceBean::getOnlineServiceCount)
                            .filter(Objects::nonNull)
                            .mapToInt(Integer::intValue)
                            .sum()
                            -
                            ihgSocialServiceOldByAres.stream()
                                    .map(IhgSocialServiceBean::getOnlineServiceCount)
                                    .filter(Objects::nonNull)
                                    .mapToInt(Integer::intValue)
                                    .sum();
                    BigDecimal socialInvolveMoneySumNew = ihgSocialServiceNewByAres.stream()
                            .map(IhgSocialServiceBean::getInvolveMoney)
                            .filter(Objects::nonNull)
                            .map(BigDecimal::valueOf)
                            .reduce(BigDecimal.ZERO, BigDecimal::add);
                    BigDecimal socialInvolveMoneySumOld = ihgSocialServiceOldByAres.stream()
                            .map(IhgSocialServiceBean::getInvolveMoney)
                            .filter(Objects::nonNull)
                            .map(BigDecimal::valueOf)
                            .reduce(BigDecimal.ZERO, BigDecimal::add);
                    BigDecimal socialInvolveMoneySum = socialInvolveMoneySumNew.subtract(socialInvolveMoneySumOld);

                    resStatisticalJson.put("areaName", areaName);
                    resStatisticalJson.put("governmentAllOrderCount", governmentAllOrderCountSum);
                    resStatisticalJson.put("governmentIhgOrderCount", governmentIhgOrderCountSum);
                    resStatisticalJson.put("governmentCreatedTime", DateUtil.formatDate(ihgGovernmentServiceNewByAres.get(0).getCreatedTime()));
                    if (governmentAllOrderCountSum != 0) {
                        resStatisticalJson.put("governmentOnlinePercent", nt.format((double) governmentIhgOrderCountSum / governmentAllOrderCountSum));
                    } else {
                        resStatisticalJson.put("governmentOnlinePercent", nt.format(0));
                    }

                    resStatisticalJson.put("socialOrderCountSum", socialOrderCountSum);
                    resStatisticalJson.put("socialEnterMarketCountSum", socialEnterMarketCountSum);
                    resStatisticalJson.put("socialOnlineServiceCountSum", socialOnlineServiceCountSum);
                    resStatisticalJson.put("socialCreatedTime", DateUtil.formatDate(ihgSocialServiceNewByAres.get(0).getCreatedTime()));
                    BigDecimal b = new BigDecimal(socialInvolveMoneySum.doubleValue());
                    double socialInvolveMoneySum2 = b.setScale(5, BigDecimal.ROUND_HALF_UP).doubleValue();
                    resStatisticalJson.put("socialInvolveMoneySum", socialInvolveMoneySum2);
                    resJsonList.add(resStatisticalJson);

                }
            } else {
                List<IhgGovernmentServiceBean> ihgGovernmentServiceBeans = ihgGovernmentServiceMapper.queryDateByTime(reqJson);
                List<IhgSocialServiceBean> ihgSocialServiceBeans = ihgSocialServiceMapper.queryDateByTime(reqJson);
                ihgSocialServiceBeans = distinctBySocialProjectName(ihgSocialServiceBeans);
                ihgGovernmentServiceBeans = distinctByGovernmentProjectName(ihgGovernmentServiceBeans);
                if (CollectionUtil.isEmpty(ihgGovernmentServiceBeans) || CollectionUtil.isEmpty(ihgSocialServiceBeans)) {
                    return WrapMapper.wrap(Wrapper.ERROR_CODE, "未查询到数据！");
                }
                List<String> areaGovernmentNames = ihgGovernmentServiceBeans.stream().map(IhgGovernmentServiceBean::getAreaName).collect(Collectors.toList());
                List<String> areaSocialNames = ihgSocialServiceBeans.stream().map(IhgSocialServiceBean::getAreaName).collect(Collectors.toList());
                areaNames.addAll(areaGovernmentNames);
                areaNames.addAll(areaSocialNames);
                areaNames = areaNames.stream().distinct().collect(Collectors.toList());
                for (String areaName : areaNames) {
                    JSONObject resStatisticalJson = new JSONObject();
                    List<IhgGovernmentServiceBean> ihgGovernmentServiceByAres = ihgGovernmentServiceBeans.stream().filter(IhgGovernmentServiceBean -> areaName.equals(IhgGovernmentServiceBean.getAreaName())).collect(Collectors.toList());
                    List<IhgSocialServiceBean> ihgSocialServiceByAres = ihgSocialServiceBeans.stream().filter(IhgSocialServiceBean -> areaName.equals(IhgSocialServiceBean.getAreaName())).collect(Collectors.toList());
                    int governmentAllOrderCountSum = ihgGovernmentServiceByAres.stream()
                            .map(IhgGovernmentServiceBean::getAllOrderCount)
                            .filter(Objects::nonNull)
                            .mapToInt(Integer::intValue)
                            .sum();
                    int governmentIhgOrderCountSum = ihgGovernmentServiceByAres.stream()
                            .map(IhgGovernmentServiceBean::getIhgOrderCount)
                            .filter(Objects::nonNull)
                            .mapToInt(Integer::intValue)
                            .sum();
                    int socialOrderCountSum = ihgSocialServiceByAres.stream()
                            .map(IhgSocialServiceBean::getOrderCount)
                            .filter(Objects::nonNull)
                            .mapToInt(Integer::intValue)
                            .sum();
                    int socialEnterMarketCountSum = ihgSocialServiceByAres.stream()
                            .map(IhgSocialServiceBean::getEnterMarketCount)
                            .filter(Objects::nonNull)
                            .mapToInt(Integer::intValue)
                            .sum();
                    int socialOnlineServiceCountSum = ihgSocialServiceByAres.stream()
                            .map(IhgSocialServiceBean::getOnlineServiceCount)
                            .filter(Objects::nonNull)
                            .mapToInt(Integer::intValue)
                            .sum();
                    BigDecimal socialInvolveMoneySum = ihgSocialServiceByAres.stream()
                            .map(IhgSocialServiceBean::getInvolveMoney)
                            .filter(Objects::nonNull)
                            .map(BigDecimal::valueOf)
                            .reduce(BigDecimal.ZERO, BigDecimal::add);

                    resStatisticalJson.put("areaName", areaName);
                    resStatisticalJson.put("governmentAllOrderCount", governmentAllOrderCountSum);
                    resStatisticalJson.put("governmentIhgOrderCount", governmentIhgOrderCountSum);
                    if (ihgGovernmentServiceByAres.size()>0){
                        resStatisticalJson.put("governmentCreatedTime", DateUtil.formatDate(ihgGovernmentServiceByAres.get(0).getCreatedTime()));
                    }
                    if (governmentAllOrderCountSum != 0) {
                        resStatisticalJson.put("governmentOnlinePercent", nt.format((double) governmentIhgOrderCountSum / governmentAllOrderCountSum));
                    } else {
                        resStatisticalJson.put("governmentOnlinePercent", nt.format(0));
                    }

                    resStatisticalJson.put("socialOrderCountSum", socialOrderCountSum);
                    resStatisticalJson.put("socialEnterMarketCountSum", socialEnterMarketCountSum);
                    resStatisticalJson.put("socialOnlineServiceCountSum", socialOnlineServiceCountSum);
                    if (ihgSocialServiceByAres.size()>0){
                        resStatisticalJson.put("socialCreatedTime", DateUtil.formatDate(ihgSocialServiceByAres.get(0).getCreatedTime()));
                    }
                    BigDecimal b = new BigDecimal(socialInvolveMoneySum.doubleValue());
                    double socialInvolveMoneySum2 = b.setScale(5, BigDecimal.ROUND_HALF_UP).doubleValue();
                    resStatisticalJson.put("socialInvolveMoneySum", socialInvolveMoneySum2);
                    resJsonList.add(resStatisticalJson);
                }
            }

            return WrapMapper.wrap(Wrapper.SUCCESS_CODE, Wrapper.SUCCESS_MESSAGE, resJsonList);
        } catch (Exception e) {
            log.error("查询统计数据报错", e);
            return WrapMapper.wrap(Wrapper.ERROR_CODE, e.getMessage());
        }
    }



    @Override
    public Wrapper querySocialStatistical(JSONObject reqJson) {
        NumberFormat nt = NumberFormat.getPercentInstance();
        nt.setMinimumFractionDigits(5);
        try {
            List<JSONObject> resJsonList = CollectionUtil.newArrayList();
            Boolean isGrowth = reqJson.getBoolean("isGrowth");
            Date startTime = reqJson.getDate("startTime");
            Date endTime = reqJson.getDate("endTime");
            if (isGrowth == null) {
                return WrapMapper.wrap(Wrapper.ERROR_CODE, "是否增长不能为空！");
            }
            if (isGrowth) {
                if (startTime == null || endTime == null) {
                    return WrapMapper.wrap(Wrapper.ERROR_CODE, "起始时间和结束时间为空！");
                }
                List<IhgSocialServiceBean> ihgSocialServiceBeans = ihgSocialServiceMapper.queryDateByTime(reqJson);
                List<IhgSocialServiceBean> ihgSocialServiceNewBeans = distinctBySocialProjectName(ihgSocialServiceBeans);
                List<IhgSocialServiceBean> ihgSocialServiceOldBeans = distinctBySocialProjectNameOld(ihgSocialServiceBeans);
                if (CollectionUtil.isEmpty(ihgSocialServiceBeans)) {
                    return WrapMapper.wrap(Wrapper.ERROR_CODE, "未查询到数据！");
                }
                List<String> projectSocialNames = ihgSocialServiceBeans.stream().map(IhgSocialServiceBean::getProjectName).distinct().collect(Collectors.toList());

                for (String projectName : projectSocialNames) {
                    JSONObject resStatisticalJson = new JSONObject();
                    List<IhgSocialServiceBean> ihgSocialServiceNewByAres = ihgSocialServiceNewBeans.stream().filter(IhgSocialServiceBean -> projectName.equals(IhgSocialServiceBean.getProjectName())).collect(Collectors.toList());
                    List<IhgSocialServiceBean> ihgSocialServiceOldByAres = ihgSocialServiceOldBeans.stream().filter(IhgSocialServiceBean -> projectName.equals(IhgSocialServiceBean.getProjectName())).collect(Collectors.toList());
                    int socialOrderCountSum = ihgSocialServiceNewByAres.stream()
                            .map(IhgSocialServiceBean::getOrderCount)
                            .filter(Objects::nonNull)
                            .mapToInt(Integer::intValue)
                            .sum()
                            -
                            ihgSocialServiceOldByAres.stream()
                                    .map(IhgSocialServiceBean::getOrderCount)
                                    .filter(Objects::nonNull)
                                    .mapToInt(Integer::intValue)
                                    .sum();
                    int socialEnterMarketCountSum = ihgSocialServiceNewByAres.stream()
                            .map(IhgSocialServiceBean::getEnterMarketCount)
                            .filter(Objects::nonNull)
                            .mapToInt(Integer::intValue)
                            .sum()
                            -
                            ihgSocialServiceOldByAres.stream()
                                    .map(IhgSocialServiceBean::getEnterMarketCount)
                                    .filter(Objects::nonNull)
                                    .mapToInt(Integer::intValue)
                                    .sum();
                    int socialOnlineServiceCountSum = ihgSocialServiceNewByAres.stream()
                            .map(IhgSocialServiceBean::getOnlineServiceCount)
                            .filter(Objects::nonNull)
                            .mapToInt(Integer::intValue)
                            .sum()
                            -
                            ihgSocialServiceOldByAres.stream()
                                    .map(IhgSocialServiceBean::getOnlineServiceCount)
                                    .filter(Objects::nonNull)
                                    .mapToInt(Integer::intValue)
                                    .sum();
                    BigDecimal socialInvolveMoneySumNew = ihgSocialServiceNewByAres.stream()
                            .map(IhgSocialServiceBean::getInvolveMoney)
                            .filter(Objects::nonNull)
                            .map(BigDecimal::valueOf)
                            .reduce(BigDecimal.ZERO, BigDecimal::add);
                    BigDecimal socialInvolveMoneySumOld = ihgSocialServiceOldByAres.stream()
                            .map(IhgSocialServiceBean::getInvolveMoney)
                            .filter(Objects::nonNull)
                            .map(BigDecimal::valueOf)
                            .reduce(BigDecimal.ZERO, BigDecimal::add);
                    BigDecimal socialInvolveMoneySum = socialInvolveMoneySumNew.subtract(socialInvolveMoneySumOld);

                    if (!ihgSocialServiceNewByAres.isEmpty()) {
                        resStatisticalJson.put("departmentName", ihgSocialServiceNewByAres.get(0).getDepartmentName());
                        resStatisticalJson.put("moduleName", ihgSocialServiceNewByAres.get(0).getModuleName());
                        resStatisticalJson.put("createdTime", DateUtil.formatDate(ihgSocialServiceNewByAres.get(0).getCreatedTime()));
                    }
                    resStatisticalJson.put("projectName", projectName);
                    resStatisticalJson.put("socialOrderCountSum", socialOrderCountSum);
                    resStatisticalJson.put("socialEnterMarketCountSum", socialEnterMarketCountSum);
                    resStatisticalJson.put("socialOnlineServiceCountSum", socialOnlineServiceCountSum);
                    BigDecimal b = new BigDecimal(socialInvolveMoneySum.doubleValue());
                    double socialInvolveMoneySum2 = b.setScale(5, BigDecimal.ROUND_HALF_UP).doubleValue();
                    resStatisticalJson.put("socialInvolveMoneySum", socialInvolveMoneySum2);
                    resJsonList.add(resStatisticalJson);
                }
            } else {
                List<IhgSocialServiceBean> ihgSocialServiceBeans = ihgSocialServiceMapper.queryDateByTime(reqJson);
                ihgSocialServiceBeans = distinctBySocialProjectName(ihgSocialServiceBeans);
                if (CollectionUtil.isEmpty(ihgSocialServiceBeans)) {
                    return WrapMapper.wrap(Wrapper.ERROR_CODE, "未查询到数据！");
                }
                List<String> projectSocialNames = ihgSocialServiceBeans.stream().map(IhgSocialServiceBean::getProjectName).distinct().collect(Collectors.toList());

                for (String projectName : projectSocialNames) {
                    JSONObject resStatisticalJson = new JSONObject();
                    List<IhgSocialServiceBean> ihgSocialServiceByAres = ihgSocialServiceBeans.stream().filter(IhgSocialServiceBean -> projectName.equals(IhgSocialServiceBean.getProjectName())).collect(Collectors.toList());
                    int socialOrderCountSum = ihgSocialServiceByAres.stream()
                            .map(IhgSocialServiceBean::getOrderCount)
                            .filter(Objects::nonNull)
                            .mapToInt(Integer::intValue)
                            .sum();
                    int socialEnterMarketCountSum = ihgSocialServiceByAres.stream()
                            .map(IhgSocialServiceBean::getEnterMarketCount)
                            .filter(Objects::nonNull)
                            .mapToInt(Integer::intValue)
                            .sum();
                    int socialOnlineServiceCountSum = ihgSocialServiceByAres.stream()
                            .map(IhgSocialServiceBean::getOnlineServiceCount)
                            .filter(Objects::nonNull)
                            .mapToInt(Integer::intValue)
                            .sum();
                    BigDecimal socialInvolveMoneySum = ihgSocialServiceByAres.stream()
                            .map(IhgSocialServiceBean::getInvolveMoney)
                            .filter(Objects::nonNull)
                            .map(BigDecimal::valueOf)
                            .reduce(BigDecimal.ZERO, BigDecimal::add);
                    if (!ihgSocialServiceByAres.isEmpty()) {
                        resStatisticalJson.put("departmentName", ihgSocialServiceByAres.get(0).getDepartmentName());
                        resStatisticalJson.put("moduleName", ihgSocialServiceByAres.get(0).getModuleName());
                        resStatisticalJson.put("createdTime", DateUtil.formatDate(ihgSocialServiceByAres.get(0).getCreatedTime()));
                    }
                    resStatisticalJson.put("projectName", projectName);
                    resStatisticalJson.put("socialOrderCountSum", socialOrderCountSum);
                    resStatisticalJson.put("socialEnterMarketCountSum", socialEnterMarketCountSum);
                    resStatisticalJson.put("socialOnlineServiceCountSum", socialOnlineServiceCountSum);
                    BigDecimal b = new BigDecimal(socialInvolveMoneySum.doubleValue());
                    double socialInvolveMoneySum2 = b.setScale(5, BigDecimal.ROUND_HALF_UP).doubleValue();
                    resStatisticalJson.put("socialInvolveMoneySum", socialInvolveMoneySum2);
                    resJsonList.add(resStatisticalJson);
                }
            }

            return WrapMapper.wrap(Wrapper.SUCCESS_CODE, Wrapper.SUCCESS_MESSAGE, resJsonList);
        } catch (Exception e) {
            log.error("查询统计数据报错", e);
            return WrapMapper.wrap(Wrapper.ERROR_CODE, e.getMessage());
        }
    }


    @Override
    public Wrapper queryGovernmentDepartStatistical(JSONObject reqJson) {
        NumberFormat nt = NumberFormat.getPercentInstance();
        nt.setMinimumFractionDigits(5);
        try {
            List<JSONObject> resJsonList = CollectionUtil.newArrayList();
//            Date startTime = reqJson.getDate("startTime");
//            Date endTime = reqJson.getDate("endTime");
//            if (startTime == null && endTime == null) {
//                return WrapMapper.wrap(Wrapper.ERROR_CODE, "起始时间和结束时间不能同时为空！");
//            }
            List<IhgGovernmentServiceBean> ihgGovernmentServiceBeans = ihgGovernmentServiceMapper.queryDateByTime(reqJson);
            ihgGovernmentServiceBeans = distinctByGovernmentProjectName(ihgGovernmentServiceBeans);
            if(CollectionUtil.isEmpty(ihgGovernmentServiceBeans)){
                return WrapMapper.wrap(Wrapper.ERROR_CODE, "未查询到数据！");
            }
            for (String departName : DEPARTMENT_NAME) {
                JSONObject resStatisticalJson = new JSONObject();
                List<IhgGovernmentServiceBean> ihgGovernmentServiceByAres = ihgGovernmentServiceBeans.stream().filter(ihgGovernmentServiceBean -> departName.equals(ihgGovernmentServiceBean.getDepartmentName())).collect(Collectors.toList());
                int governmentAllOrderCountSum = ihgGovernmentServiceByAres.stream()
                        .map(IhgGovernmentServiceBean::getAllOrderCount)
                        .filter(Objects::nonNull)
                        .mapToInt(Integer::intValue)
                        .sum();
                int governmentIhgOrderCountSum = ihgGovernmentServiceByAres.stream()
                        .map(IhgGovernmentServiceBean::getIhgOrderCount)
                        .filter(Objects::nonNull)
                        .mapToInt(Integer::intValue)
                        .sum();
                BigDecimal governmentIhgAllOrderMoneySum = ihgGovernmentServiceByAres.stream()
                        .map(IhgGovernmentServiceBean::getAllOrderMoney)
                        .filter(Objects::nonNull)
                        .map(BigDecimal::valueOf)
                        .reduce(BigDecimal.ZERO, BigDecimal::add);
                BigDecimal governmentIhgIhgOrderMoneySum = ihgGovernmentServiceByAres.stream()
                        .map(IhgGovernmentServiceBean::getIhgOrderMoney)
                        .filter(Objects::nonNull)
                        .map(BigDecimal::valueOf)
                        .reduce(BigDecimal.ZERO, BigDecimal::add);

                resStatisticalJson.put("departmentName", departName);
                resStatisticalJson.put("governmentAllOrderCount", governmentAllOrderCountSum);
                resStatisticalJson.put("governmentIhgOrderCount", governmentIhgOrderCountSum);
                resStatisticalJson.put("governmentIhgAllOrderMoneySum", governmentIhgAllOrderMoneySum.doubleValue());
                resStatisticalJson.put("governmentIhgIhgOrderMoneySum", governmentIhgIhgOrderMoneySum.doubleValue());
                if(CollectionUtil.isNotEmpty(ihgGovernmentServiceByAres)){
                    resStatisticalJson.put("createdTime", DateUtil.formatDate(ihgGovernmentServiceByAres.get(0).getCreatedTime()));
                }
                if (governmentAllOrderCountSum != 0) {
                    resStatisticalJson.put("governmentOnlinePercent", nt.format((double)governmentIhgOrderCountSum / governmentAllOrderCountSum));
                } else {
                    resStatisticalJson.put("governmentOnlinePercent", nt.format(0));
                }
                resJsonList.add(resStatisticalJson);
            }
            return WrapMapper.wrap(Wrapper.SUCCESS_CODE, Wrapper.SUCCESS_MESSAGE, groupedList(resJsonList));
        } catch (Exception e) {
            log.error("查询统计数据报错", e);
            return WrapMapper.wrap(Wrapper.ERROR_CODE, e.getMessage());
        }
    }


    @Override
    public Wrapper queryGovernmentStatistical(JSONObject reqJson) {
        NumberFormat nt = NumberFormat.getPercentInstance();
        nt.setMinimumFractionDigits(5);
        try {
            List<JSONObject> resJsonList = CollectionUtil.newArrayList();
            Boolean isGrowth = reqJson.getBoolean("isGrowth");
            Date startTime = reqJson.getDate("startTime");
            Date endTime = reqJson.getDate("endTime");
            if (isGrowth == null) {
                return WrapMapper.wrap(Wrapper.ERROR_CODE, "是否增长不能为空！");
            }
            if (isGrowth) {
                if (startTime == null || endTime == null) {
                    return WrapMapper.wrap(Wrapper.ERROR_CODE, "起始时间和结束时间为空！");
                }
                List<IhgGovernmentServiceBean> ihgGovernmentServiceBeans = ihgGovernmentServiceMapper.queryDateByTime(reqJson);
                List<IhgGovernmentServiceBean> ihgGovernmentServiceBeansNew = distinctByGovernmentProjectName(ihgGovernmentServiceBeans);
                List<IhgGovernmentServiceBean> ihgGovernmentServiceBeansOld = distinctByGovernmentProjectNameOld(ihgGovernmentServiceBeans);
                if (CollectionUtil.isEmpty(ihgGovernmentServiceBeans)) {
                    return WrapMapper.wrap(Wrapper.ERROR_CODE, "未查询到数据！");
                }
                List<String> governmentProjectNamesNew = ihgGovernmentServiceBeansNew.stream().map(IhgGovernmentServiceBean::getProjectName).distinct().collect(Collectors.toList());
                for (String projectName : governmentProjectNamesNew) {
                    JSONObject resStatisticalJson = new JSONObject();
                    List<IhgGovernmentServiceBean> ihgGovernmentServiceNewByAres = ihgGovernmentServiceBeansNew.stream().filter(ihgGovernmentServiceBean -> projectName.equals(ihgGovernmentServiceBean.getProjectName())).collect(Collectors.toList());
                    List<IhgGovernmentServiceBean> ihgGovernmentServiceOldByAres = ihgGovernmentServiceBeansOld.stream().filter(ihgGovernmentServiceBean -> projectName.equals(ihgGovernmentServiceBean.getProjectName())).collect(Collectors.toList());
                    int governmentAllOrderCountSum = ihgGovernmentServiceNewByAres.stream()
                            .map(IhgGovernmentServiceBean::getAllOrderCount)
                            .filter(Objects::nonNull)
                            .mapToInt(Integer::intValue)
                            .sum()
                            -
                            ihgGovernmentServiceOldByAres.stream()
                                    .map(IhgGovernmentServiceBean::getAllOrderCount)
                                    .filter(Objects::nonNull)
                                    .mapToInt(Integer::intValue)
                                    .sum();
                    int governmentIhgOrderCountSum = ihgGovernmentServiceNewByAres.stream()
                            .map(IhgGovernmentServiceBean::getIhgOrderCount)
                            .filter(Objects::nonNull)
                            .mapToInt(Integer::intValue)
                            .sum()
                            -
                            ihgGovernmentServiceOldByAres.stream()
                                    .map(IhgGovernmentServiceBean::getIhgOrderCount)
                                    .filter(Objects::nonNull)
                                    .mapToInt(Integer::intValue)
                                    .sum();
                    if (!ihgGovernmentServiceNewByAres.isEmpty()) {
                        resStatisticalJson.put("departmentName", ihgGovernmentServiceNewByAres.get(0).getDepartmentName());
                        resStatisticalJson.put("projectName", ihgGovernmentServiceNewByAres.get(0).getProjectName());
                        resStatisticalJson.put("governmentAllOrderCount", governmentAllOrderCountSum);
                        resStatisticalJson.put("governmentIhgOrderCount", governmentIhgOrderCountSum);
                        if (CollectionUtil.isNotEmpty(ihgGovernmentServiceNewByAres)) {
                            resStatisticalJson.put("createdTime", DateUtil.formatDate(ihgGovernmentServiceNewByAres.get(0).getCreatedTime()));
                        }
                        if (governmentAllOrderCountSum != 0) {
                            resStatisticalJson.put("governmentOnlinePercent", nt.format((double) governmentIhgOrderCountSum / governmentAllOrderCountSum));
                        } else {
                            resStatisticalJson.put("governmentOnlinePercent", nt.format(0));
                        }
                        resJsonList.add(resStatisticalJson);
                    }
                }
            } else {
                List<IhgGovernmentServiceBean> ihgGovernmentServiceBeans = ihgGovernmentServiceMapper.queryDateByTime(reqJson);
                ihgGovernmentServiceBeans = distinctByGovernmentProjectName(ihgGovernmentServiceBeans);
                if (CollectionUtil.isEmpty(ihgGovernmentServiceBeans)) {
                    return WrapMapper.wrap(Wrapper.ERROR_CODE, "未查询到数据！");
                }
                List<String> governmentProjectNames = ihgGovernmentServiceBeans.stream().map(IhgGovernmentServiceBean::getProjectName).distinct().collect(Collectors.toList());
                for (String projectName : governmentProjectNames) {
                    JSONObject resStatisticalJson = new JSONObject();
                    List<IhgGovernmentServiceBean> ihgGovernmentServiceByAres = ihgGovernmentServiceBeans.stream().filter(ihgGovernmentServiceBean -> projectName.equals(ihgGovernmentServiceBean.getProjectName())).collect(Collectors.toList());
                    int governmentAllOrderCountSum = ihgGovernmentServiceByAres.stream()
                            .map(IhgGovernmentServiceBean::getAllOrderCount)
                            .filter(Objects::nonNull)
                            .mapToInt(Integer::intValue)
                            .sum();
                    int governmentIhgOrderCountSum = ihgGovernmentServiceByAres.stream()
                            .map(IhgGovernmentServiceBean::getIhgOrderCount)
                            .filter(Objects::nonNull)
                            .mapToInt(Integer::intValue)
                            .sum();
                    if (!ihgGovernmentServiceByAres.isEmpty()) {
                        resStatisticalJson.put("departmentName", ihgGovernmentServiceByAres.get(0).getDepartmentName());
                        resStatisticalJson.put("projectName", ihgGovernmentServiceByAres.get(0).getProjectName());
                        resStatisticalJson.put("governmentAllOrderCount", governmentAllOrderCountSum);
                        resStatisticalJson.put("governmentIhgOrderCount", governmentIhgOrderCountSum);
                        if (CollectionUtil.isNotEmpty(ihgGovernmentServiceByAres)) {
                            resStatisticalJson.put("createdTime", DateUtil.formatDate(ihgGovernmentServiceByAres.get(0).getCreatedTime()));
                        }
                        if (governmentAllOrderCountSum != 0) {
                            resStatisticalJson.put("governmentOnlinePercent", nt.format((double) governmentIhgOrderCountSum / governmentAllOrderCountSum));
                        } else {
                            resStatisticalJson.put("governmentOnlinePercent", nt.format(0));
                        }
                        resJsonList.add(resStatisticalJson);
                    }
                }
            }
            return WrapMapper.wrap(Wrapper.SUCCESS_CODE, Wrapper.SUCCESS_MESSAGE, groupedList(resJsonList));
        } catch (Exception e) {
            log.error("查询统计数据报错", e);
            return WrapMapper.wrap(Wrapper.ERROR_CODE, e.getMessage());
        }
    }

    @Override
    public Wrapper queryGovernmentStatisticalByProjectName(JSONObject reqJson) {
        NumberFormat nt = NumberFormat.getPercentInstance();
        nt.setMinimumFractionDigits(5);
        try {
            List<JSONObject> resDataAllList = CollectionUtil.newArrayList();
            List<IhgGovernmentServiceBean> ihgGovernmentServiceBeans = ihgGovernmentServiceMapper.queryDateByTime(reqJson);
            ihgGovernmentServiceBeans = distinctByGovernmentProjectName(ihgGovernmentServiceBeans);
            if (CollectionUtil.isEmpty(ihgGovernmentServiceBeans)) {
                return WrapMapper.wrap(Wrapper.ERROR_CODE, "未查询到数据！");
            }
            List<String> governmentProjectNames = ihgGovernmentServiceBeans.stream().map(IhgGovernmentServiceBean::getProjectName).collect(Collectors.toList());
            List<String> projectNames = governmentProjectNames.stream().distinct().collect(Collectors.toList());
            for (String projectName : projectNames) {
                JSONArray resDataArray = new JSONArray();
                JSONObject resStatisticalJson = new JSONObject();
                String departmentName = null;
                List<String> areaGovernmentNames = ihgGovernmentServiceBeans.stream().map(IhgGovernmentServiceBean::getAreaName).distinct().collect(Collectors.toList());
                for (String areaGovernmentName : areaGovernmentNames) {
                    JSONObject resStatisticalDataJson = new JSONObject();
                    List<IhgGovernmentServiceBean> ihgGovernmentServiceByAres = ihgGovernmentServiceBeans.stream()
                            .filter(IhgGovernmentServiceBean -> areaGovernmentName.equals(IhgGovernmentServiceBean.getAreaName()))
                            .filter(IhgGovernmentServiceBean -> projectName.equals(IhgGovernmentServiceBean.getProjectName()))
                            .collect(Collectors.toList());
                    int governmentAllOrderCountSum = ihgGovernmentServiceByAres.stream()
                            .map(IhgGovernmentServiceBean::getAllOrderCount)
                            .filter(Objects::nonNull)
                            .mapToInt(Integer::intValue)
                            .sum();
                    BigDecimal governmentAllOrderMoneySum = ihgGovernmentServiceByAres.stream()
                            .map(IhgGovernmentServiceBean::getAllOrderMoney)
                            .filter(Objects::nonNull)
                            .map(BigDecimal::valueOf)
                            .reduce(BigDecimal.ZERO, BigDecimal::add);
                    int governmentIhgOrderCountSum = ihgGovernmentServiceByAres.stream()
                            .map(IhgGovernmentServiceBean::getIhgOrderCount)
                            .filter(Objects::nonNull)
                            .mapToInt(Integer::intValue)
                            .sum();
                    BigDecimal governmentIhgOrderMoneySum = ihgGovernmentServiceByAres.stream()
                            .map(IhgGovernmentServiceBean::getIhgOrderMoney)
                            .filter(Objects::nonNull)
                            .map(BigDecimal::valueOf)
                            .reduce(BigDecimal.ZERO, BigDecimal::add);
                    if(!ObjectUtil.isEmpty(ihgGovernmentServiceByAres)){
                        departmentName = ihgGovernmentServiceByAres.get(0).getDepartmentName();
                    }
                    resStatisticalDataJson.put("areaName",areaGovernmentName);
                    resStatisticalDataJson.put("governmentAllOrderCountSum",governmentAllOrderCountSum);
                    resStatisticalDataJson.put("governmentAllOrderMoneySum",governmentAllOrderMoneySum.doubleValue());
                    resStatisticalDataJson.put("governmentIhgOrderCountSum",governmentIhgOrderCountSum);
                    resStatisticalDataJson.put("governmentIhgOrderMoneySum",governmentIhgOrderMoneySum.doubleValue());
                    if(!ObjectUtil.isEmpty(ihgGovernmentServiceByAres)){
                        resStatisticalDataJson.put("createdTime", DateUtil.formatDate(ihgGovernmentServiceByAres.get(0).getCreatedTime()));
                    }
                    resDataArray.add(resStatisticalDataJson);
                }

                resStatisticalJson.put("departmentName",departmentName);
                resStatisticalJson.put("projectName",projectName);
                resStatisticalJson.put("resDataArray",resDataArray);
                resDataAllList.add(resStatisticalJson);
            }

            return WrapMapper.wrap(Wrapper.SUCCESS_CODE, Wrapper.SUCCESS_MESSAGE, groupedList(resDataAllList));
        } catch (Exception e) {
            log.error("查询统计数据报错", e);
            return WrapMapper.wrap(Wrapper.ERROR_CODE, e.getMessage());
        }
    }

    @Override
    public Wrapper querySocialStatisticalByProjectName(JSONObject reqJson) {
        NumberFormat nt = NumberFormat.getPercentInstance();
        nt.setMinimumFractionDigits(4);
        try {
            List<JSONObject> resDataAllList = CollectionUtil.newArrayList();
            List<IhgSocialServiceBean> ihgSocialServiceBeans = ihgSocialServiceMapper.queryDateByTime(reqJson);
            ihgSocialServiceBeans = distinctBySocialProjectName(ihgSocialServiceBeans);
            if (CollectionUtil.isEmpty(ihgSocialServiceBeans)) {
                return WrapMapper.wrap(Wrapper.ERROR_CODE, "未查询到数据！");
            }
            List<String> socialProjectNames = ihgSocialServiceBeans.stream().map(IhgSocialServiceBean::getProjectName).collect(Collectors.toList());
            List<String> projectNames = socialProjectNames.stream().distinct().collect(Collectors.toList());
            for (String projectName : projectNames) {
                JSONArray resDataArray = new JSONArray();
                JSONObject resStatisticalJson = new JSONObject();
                String departmentName = null;
                String moduleName = null;
                List<String> areaSocialNames = ihgSocialServiceBeans.stream().map(IhgSocialServiceBean::getAreaName).distinct().collect(Collectors.toList());
                for (String areaSocialName : areaSocialNames) {
                    JSONObject resSocialDataJson = new JSONObject();
                    List<IhgSocialServiceBean> ihgSocialServiceByAres = ihgSocialServiceBeans.stream()
                            .filter(IhgSocialServiceBean -> areaSocialName.equals(IhgSocialServiceBean.getAreaName()))
                            .filter(IhgSocialServiceBean -> projectName.equals(IhgSocialServiceBean.getProjectName()))
                            .collect(Collectors.toList());
                    int socialOrderCountSum = ihgSocialServiceByAres.stream()
                            .map(IhgSocialServiceBean::getOrderCount)
                            .filter(Objects::nonNull)
                            .mapToInt(Integer::intValue)
                            .sum();
                    int socialEnterMarketCountSum = ihgSocialServiceByAres.stream()
                            .map(IhgSocialServiceBean::getEnterMarketCount)
                            .filter(Objects::nonNull)
                            .mapToInt(Integer::intValue)
                            .sum();
                    int socialOnlineServiceCountSum = ihgSocialServiceByAres.stream()
                            .map(IhgSocialServiceBean::getOnlineServiceCount)
                            .filter(Objects::nonNull)
                            .mapToInt(Integer::intValue)
                            .sum();
                    BigDecimal socialInvolveMoneySum = ihgSocialServiceByAres.stream()
                            .map(IhgSocialServiceBean::getInvolveMoney)
                            .filter(Objects::nonNull)
                            .map(BigDecimal::valueOf)
                            .reduce(BigDecimal.ZERO, BigDecimal::add);

                    if(!ObjectUtil.isEmpty(ihgSocialServiceByAres)){
                        departmentName = ihgSocialServiceByAres.get(0).getDepartmentName();
                        moduleName = ihgSocialServiceByAres.get(0).getModuleName();
                    }
                    resSocialDataJson.put("areaName",areaSocialName);
                    resSocialDataJson.put("socialOrderCountSum",socialOrderCountSum);
                    resSocialDataJson.put("socialEnterMarketCountSum",socialEnterMarketCountSum);
                    resSocialDataJson.put("socialOnlineServiceCountSum",socialOnlineServiceCountSum);
                    resSocialDataJson.put("socialInvolveMoneySum",socialInvolveMoneySum.doubleValue());
                    if (ihgSocialServiceByAres!=null && ihgSocialServiceByAres.size()>0){
                        resSocialDataJson.put("createdTime", DateUtil.formatDate(ihgSocialServiceByAres.get(0).getCreatedTime()));
                    }
                    resDataArray.add(resSocialDataJson);
                }
                resStatisticalJson.put("departmentName",departmentName);
                resStatisticalJson.put("moduleName",moduleName);
                resStatisticalJson.put("projectName",projectName);
                resStatisticalJson.put("resDataArray",resDataArray);
                resDataAllList.add(resStatisticalJson);
            }
            return WrapMapper.wrap(Wrapper.SUCCESS_CODE, Wrapper.SUCCESS_MESSAGE, groupedList(resDataAllList));
        } catch (Exception e) {
            log.error("查询统计数据报错", e);
            return WrapMapper.wrap(Wrapper.ERROR_CODE, e.getMessage());
        }
    }

    @Override
    public PageInfo querySocialLastDay(IHgQueryDto iHgQueryDto) {
        PageHelper.startPage(iHgQueryDto.getPageNum(),iHgQueryDto.getPageSize());
        List<IhgSocialServiceBean> list = ihgSocialServiceMapper.selectLastByPage(iHgQueryDto);
//         list = distinctBySocialProjectName(list);
        return new PageInfo(list);
    }

    @Override
    public PageInfo queryGovLastDay(IHgQueryDto iHgQueryDto) {
        PageHelper.startPage(iHgQueryDto.getPageNum(),iHgQueryDto.getPageSize());
        List<IhgGovernmentServiceBean> list = ihgGovernmentServiceMapper.selectLastByPage(iHgQueryDto);
//         list = distinctByGovernmentProjectName(list);
        return new PageInfo(list);
    }


    @Override
    public Wrapper importGovernmentData(MultipartFile file,String creator) {
        try {
            ExcelReader reader = ExcelUtil.getReader(file.getInputStream());
            List<Map<String, Object>> ExcelList = reader.readAll();
            if (CollectionUtil.isEmpty(ExcelList)) {
                return WrapMapper.wrap(Wrapper.ERROR_CODE, "Excel不能为空！");
            }
            for (Map<String, Object> excelMap : ExcelList) {
                IhgGovernmentServiceBean ihgGovernmentServiceBean = new IhgGovernmentServiceBean();
                ihgGovernmentServiceBean.setDepartmentName(Convert.toStr(excelMap.get("部门名称")).trim());
                ihgGovernmentServiceBean.setProjectName(Convert.toStr(excelMap.get("服务项目名称")).trim());
                ihgGovernmentServiceBean.setAllOrderCount(Convert.toInt(excelMap.get("所有渠道办理的总办件数")));
                ihgGovernmentServiceBean.setAllOrderMoney(Convert.toDouble(excelMap.get("所有渠道办理涉及的总金额（万元）")));
                ihgGovernmentServiceBean.setIhgOrderCount(Convert.toInt(excelMap.get("i黄冈办理的办件数")));
                ihgGovernmentServiceBean.setIhgOrderMoney(Convert.toDouble(excelMap.get("i黄冈办理涉及的金额（万元）")));
                ihgGovernmentServiceBean.setAreaName(Convert.toStr(excelMap.get("区划地名")).trim());
                ihgGovernmentServiceBean.setCreator(creator);

                String createdTime = Convert.toStr(excelMap.get("填报时间"));
                try {
                    ihgGovernmentServiceBean.setCreatedTime(DateUtil.parse(createdTime, DatePattern.NORM_DATETIME_PATTERN));
                }catch (Exception e){
                    createdTime = createdTime.replace("年","-").replace("月","-").replace("日","");
                    ihgGovernmentServiceBean.setCreatedTime(DateUtil.parse(createdTime, DatePattern.NORM_DATE_PATTERN));
                }
                if(StrUtil.isNotEmpty(ihgGovernmentServiceBean.getAreaName())&&StrUtil.isNotEmpty(ihgGovernmentServiceBean.getDepartmentName())){
                    ihgGovernmentServiceMapper.addData(ihgGovernmentServiceBean);
                }
            }
            return WrapMapper.wrap(Wrapper.SUCCESS_CODE, Wrapper.SUCCESS_MESSAGE, "导入政府服务数据成功");
        } catch (Exception e) {
            log.error("导入政府服务数据报错", e);
            return WrapMapper.wrap(Wrapper.ERROR_CODE, e.getMessage());
        }
    }

    @Override
    public Wrapper importSocialData(MultipartFile file,String creator) {
        try {
            ExcelReader reader = ExcelUtil.getReader(file.getInputStream());
            List<Map<String, Object>> ExcelList = reader.readAll();
            if (CollectionUtil.isEmpty(ExcelList)) {
                return WrapMapper.wrap(Wrapper.ERROR_CODE, "Excel不能为空！");
            }
            ExecutorService executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
            List<Future<?>> futures = new ArrayList<>();

            for (Map<String, Object> excelMap : ExcelList) {
                Future<?> future = executorService.submit(() -> {
                    IhgSocialServiceBean ihgSocialServiceBean = new IhgSocialServiceBean();
                    ihgSocialServiceBean.setDepartmentName(Convert.toStr(excelMap.get("部门名称")).trim());
                    ihgSocialServiceBean.setModuleName(Convert.toStr(excelMap.get("模块名称")).trim());
                    String projectName2 = Convert.toStr(excelMap.get("服务项目名称")).trim();
                    projectName2.replace("（仅市区）","");
                    projectName2.replace(" ","");
                    ihgSocialServiceBean.setProjectName(projectName2);
                    ihgSocialServiceBean.setOrderCount(Convert.toInt(excelMap.get("业务量")));
                    ihgSocialServiceBean.setEnterMarketCount(Convert.toInt(excelMap.get("进驻市场主体数量")));
                    ihgSocialServiceBean.setOnlineServiceCount(Convert.toInt(excelMap.get("上线服务或产品数")));
                    ihgSocialServiceBean.setInvolveMoney(Convert.toDouble(excelMap.get("涉及资金（万元）")));
                    ihgSocialServiceBean.setCreator(creator);
                    ihgSocialServiceBean.setAreaName(Convert.toStr(excelMap.get("区域名称")).trim());
                    //填报时间
                    String createdTime = Convert.toStr(excelMap.get("填报时间"));
                    try {
                        ihgSocialServiceBean.setCreatedTime(DateUtil.parse(createdTime, DatePattern.NORM_DATETIME_PATTERN));
                    }catch (Exception e){
                        ihgSocialServiceBean.setCreatedTime(new Date());
                    }
                    if(StrUtil.isNotEmpty(ihgSocialServiceBean.getAreaName())&&StrUtil.isNotEmpty(ihgSocialServiceBean.getDepartmentName())){
                        ihgSocialServiceMapper.addData(ihgSocialServiceBean);
                    }
                });
                futures.add(future);
            }
            // 等待所有任务完成
            for (Future<?> future : futures) {
                try {
                    future.get();
                } catch (InterruptedException | ExecutionException e) {
                    log.error("执行出错", e);
                }
            }
            // 关闭线程池
            executorService.shutdown();
            return WrapMapper.wrap(Wrapper.SUCCESS_CODE, Wrapper.SUCCESS_MESSAGE, "导入社会服务数据成功");
        } catch (Exception e) {
            log.error("导入社会服务数据报错", e);
            return WrapMapper.wrap(Wrapper.ERROR_CODE, e.getMessage());
        }
    }

    public List<JSONObject> groupedList(List<JSONObject> resJsonList) {
        //排序
        Map<String, List<JSONObject>> groupedList = resJsonList.stream().collect(Collectors.groupingBy(json -> json.getString("departmentName")));
        List<JSONObject> sortedList = DEPARTMENT_NAME.stream()
                .flatMap(department -> groupedList.getOrDefault(department, Collections.emptyList()).stream())
                .collect(Collectors.toList());
        Set<String> departmentNamesInSortedList = sortedList.stream()
                .map(json -> json.getString("departmentName"))
                .collect(Collectors.toSet());
        resJsonList.stream()
                .filter(json -> !departmentNamesInSortedList.contains(json.getString("departmentName")))
                .forEach(sortedList::add);
        return sortedList;
    }

    /**
     * 依据areaName和projectName对IhgGovernmentServiceBean列表去重，同时保留createdTime最新的那条数据
     * @param list
     * @return
     */
    public List<IhgGovernmentServiceBean> distinctByGovernmentProjectName(List<IhgGovernmentServiceBean> list) {
        return list.stream()
                .collect(Collectors.groupingBy(
                        bean -> Arrays.asList(bean.getAreaName(), bean.getProjectName()),
                        Collectors.maxBy(Comparator.comparing(IhgGovernmentServiceBean::getCreatedTime))
                ))
                .values().stream()
                .filter(Optional::isPresent)
                .map(Optional::get)
                .collect(Collectors.toList());
    }

    /**
     * 依据areaName和projectName对IhgGovernmentServiceBean列表去重，同时保留createdTime最老的那条数据
     * @param list
     * @return
     */
    public List<IhgGovernmentServiceBean> distinctByGovernmentProjectNameOld(List<IhgGovernmentServiceBean> list) {
        return list.stream()
                .collect(Collectors.groupingBy(
                        bean -> Arrays.asList(bean.getAreaName(), bean.getProjectName()),
                        Collectors.minBy(Comparator.comparing(IhgGovernmentServiceBean::getCreatedTime))
                ))
                .values().stream()
                .filter(Optional::isPresent)
                .map(Optional::get)
                .collect(Collectors.toList());
    }

    /**
     * 依据areaName和projectName对IhgSocialServiceBean列表去重，同时保留createdTime最新的那条数据
     * @param list
     * @return
     */
    public List<IhgSocialServiceBean> distinctBySocialProjectName(List<IhgSocialServiceBean> list) {
        return list.stream()
                .collect(Collectors.groupingBy(
                        bean -> Arrays.asList(bean.getAreaName(), bean.getProjectName()),
                        Collectors.maxBy(Comparator.comparing(IhgSocialServiceBean::getCreatedTime))
                ))
                .values().stream()
                .filter(Optional::isPresent)
                .map(Optional::get)
                .collect(Collectors.toList());
    }

    /**
     * 依据areaName和projectName对IhgSocialServiceBean列表去重，同时保留createdTime最老的那条数据
     * @param list
     * @return
     */
    public List<IhgSocialServiceBean> distinctBySocialProjectNameOld(List<IhgSocialServiceBean> list) {
        return list.stream()
                .collect(Collectors.groupingBy(
                        bean -> Arrays.asList(bean.getAreaName(), bean.getProjectName()),
                        Collectors.minBy(Comparator.comparing(IhgSocialServiceBean::getCreatedTime))
                ))
                .values().stream()
                .filter(Optional::isPresent)
                .map(Optional::get)
                .collect(Collectors.toList());
    }

}
